﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using System.Threading;
using System.Data.OleDb;
using System.IO;
using System.Diagnostics;
using System.Reflection;

namespace Pet
{
    public partial class Main : Form
    {
        #region API
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out   int ID);
        #endregion

        public Main()
        {
            InitializeComponent();
        }
        #region 全局变量
        public static string account;
        private static string choiceFilePath = Application.StartupPath + "\\choice.ini";
        private static string configFilePath = Application.StartupPath + "\\config.ini";
        string excelUrl = string.Empty;//excel路径
        int choiceCount = 0;//被勾选的帐套数量
        public static string database;//当前帐套
        public static string databaseA;//当前帐套
        string time = string.Empty;//当前时间
        int errorInfo = 0;//错误信息
        private string saleType;//销售级别
        private string cinvCode;//存货编码
        private string cinvName;//存货名称
        private string cinvStd;//规格型号
        private string cinvcCode;//存货分类
        private string iInvWeight;//净重
        private string cComUnitCode;//主计量单位
        string iTaxUnitPrice = string.Empty;//含税单价
        string iTaxUnitPriceX = string.Empty;//无税单价
        string dStartDate = string.Empty;//起始日期
        string dEnableDate = string.Empty;//结束日期
        bool dEDate = false;
        string dbtype = string.Empty;//帐套类型
        string tempCinvCode = string.Empty;//临时存货编码
        string logTime = string.Empty;//记录日志时的时间
        string btnTime = string.Empty;//请购单日期
        int dgvCount = 0;
        string posPrice = string.Empty;//pos价格
        string posdEndDate = string.Empty;//pos
        string posdStartDate = string.Empty;//pos
        static StringBuilder sb1;
        static StringBuilder sb2;
        static StringBuilder sb3;
        static StringBuilder sb4;
        SqlConnection con;
        int partId = 0;
        //请购单
        string nid = string.Empty;
        string uid = string.Empty;
        int saveOK = 0;
        string id = string.Empty;
        string cCode = string.Empty;
        string dDate = string.Empty;
        string cInvCode = string.Empty;
        string fQuantity = string.Empty;
        string tempCode = string.Empty;
        string bz = string.Empty;
        //采购入库单
        string tempOrder = string.Empty;//临时订单号
        string tempZT = string.Empty;//临时帐套号
        string zt = string.Empty;//帐套
        string ztid = string.Empty;//帐套对应id
        string order = string.Empty;//订单号
        string code = string.Empty;//存货编码
        string count = string.Empty;//存货数量
        DateTime dateXX;//日期
        string priceA = string.Empty;
        string priceB = string.Empty;
        int poidA = 0;//采购主表最大id
        int poidB = 0;//采购子表最大id
        int rdidA = 0;//入库单主表最大id
        int rdidB = 0;//入库单子表最大id
        string row = string.Empty;
        string oldID = string.Empty;
        bool zbAok = true;
        bool zbBok = true;
        int logType = 0;
        double[] sum = new double[5];
        int ii = 0;
        string nullCode = string.Empty;//检测为不存在的存货编码
        //其他
        int otherType = 0;
        //客户导出
        string cusName = string.Empty;
        string cusId = string.Empty;
        string cccname = string.Empty;
        string ccusrankname = string.Empty;
        string ccusname = string.Empty;
        string ccusabbname = string.Empty;
        string ccusperson = string.Empty;
        string ccusaddress = string.Empty;
        string ccusphone = string.Empty;
        string ccushand = string.Empty;
        string dcusdevdate = string.Empty;
        string denddate = string.Empty;
        string cpersonname = string.Empty;
        string cpersoncode = string.Empty;
        string ccuscode = string.Empty;

        #endregion

        private void Main_Load(object sender, EventArgs e)
        {
            sb1 = new StringBuilder(255);
            sb2 = new StringBuilder(255);
            sb3 = new StringBuilder(255);
            sb4 = new StringBuilder(255);
            GetPrivateProfileString("config", "server", "", sb1, 255, configFilePath);
            GetPrivateProfileString("config", "id", "", sb2, 255, configFilePath);
            GetPrivateProfileString("config", "pwd", "", sb3, 255, configFilePath);
            GetPrivateProfileString("config", "logPath", "", sb4, 255, configFilePath);
            LoadYear();
            readChoiceYear();
            LoadZT();
            readChoice();
            data();
            label4.Text = "";
        }

        #region 读帐套和年度
        private void LoadZT()
        {
            lvZT.Items.Clear();
            try
            {
                if (lsYear.SelectedItem.ToString() == "")
                {
                }
            }
            catch
            {
                return;
            }
            string sql = string.Empty;
            if (account.ToLower() == "all")
            {
                sql = string.Format("select distinct(a.cacc_id),cacc_name,cFinType,cFinKind from ua_account as a inner join UA_Period as b on a.cacc_id=b.cacc_id where b.iyear='{0}'", lsYear.SelectedItem.ToString());
            }
            else
            {
                sql = string.Format("select distinct(a.cacc_id),cacc_name,cFinType,cFinKind from ua_account as a inner join UA_Period as b on a.cacc_id=b.cacc_id where b.iyear='{0}' and a.cfinkind='{1}'", lsYear.SelectedItem.ToString(), account.ToLower());
            }
            SqlCommand com = new SqlCommand(sql, DBHelper.con);
            DBHelper.con.Open();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                while (sdr.Read())
                {
                    string id = sdr["cacc_id"].ToString();
                    string name = sdr["cacc_name"].ToString();
                    string type = sdr["cFinType"].ToString();
                    string group = sdr["cFinKind"].ToString();
                    ListViewItem lvi = new ListViewItem();
                    lvi.SubItems.Add(name);
                    lvi.SubItems.Add(id);
                    lvi.SubItems.Add(type);
                    lvi.SubItems.Add(group);
                    lvZT.Items.Add(lvi);
                }
            }
            DBHelper.con.Close();
        }

        private void LoadYear()
        {
            string sql = "select distinct(iyear) from ua_account_sub where iyear <> 9999 order by iyear desc";
            SqlCommand com = new SqlCommand(sql, DBHelper.con);
            DBHelper.con.Open();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                while (sdr.Read())
                {
                    string year = sdr["iyear"].ToString();
                    lsYear.Items.Add(year);
                }
            }
            DBHelper.con.Close();

        }
        #endregion

        #region 配置文件
        /// <summary>
        /// 记录选择的帐套
        /// </summary>
        private void recordChoice()
        {
            for (int i = 0; i < lvZT.Items.Count; i++)
            {
                if (lvZT.Items[i].Checked == true)
                {
                    choiceCount++;
                    WritePrivateProfileString(account.ToLower(), lvZT.Items[i].SubItems[2].Text.ToString(), "1", choiceFilePath);
                }
                else
                {
                    WritePrivateProfileString(account.ToLower(), lvZT.Items[i].SubItems[2].Text.ToString(), "0", choiceFilePath);
                }
            }
            for (int i = 0; i < lsYear.Items.Count; i++)
            {
                if (lsYear.GetSelected(i) == true)
                {
                    WritePrivateProfileString("YEAR", i.ToString(), "1", choiceFilePath);
                }
                else
                {
                    WritePrivateProfileString("YEAR", i.ToString(), "0", choiceFilePath);
                }
            }
        }

        /// <summary>
        /// 读记录的帐套选择信息
        /// </summary>
        private void readChoice()
        {
            try
            {
                for (int i = 0; i < lvZT.Items.Count; i++)
                {
                    StringBuilder sb = new StringBuilder(255);
                    GetPrivateProfileString(account.ToLower(), lvZT.Items[i].SubItems[2].Text.ToString(), "", sb, 255, choiceFilePath);
                    if (Convert.ToInt32(sb.ToString()) == 1)
                    {
                        lvZT.Items[i].Checked = true;
                    }
                }
            }
            catch
            {
            }
        }

        private void readChoiceYear()
        {
            try
            {
                for (int i = 0; i < lsYear.Items.Count; i++)
                {
                    StringBuilder sbr = new StringBuilder(255);
                    GetPrivateProfileString("YEAR", i.ToString(), "", sbr, 255, choiceFilePath);
                    if (Convert.ToInt32(sbr.ToString()) == 1)
                    {
                        lsYear.SetSelected(i, true);
                    }
                }
            }
            catch
            {
            }
        }
        #endregion

        private void lsYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadZT();
            readChoice();
        }

        /// <summary>
        /// 导入按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCHOK_Click(object sender, EventArgs e)
        {
            recordChoice();
            #region 导入前的判断
            if (dgvZT.Rows.Count < 1)
            {
                MessageBox.Show("没有选择数据源！");
                choiceCount = 0;
                return;
            }
            if (choiceCount < 1)
            {
                MessageBox.Show("没有选择帐套！");
                choiceCount = 0;
                return;
            }
            try
            {
                if (lsYear.SelectedItem.ToString() == "")
                {
                }
            }
            catch
            {
                MessageBox.Show("没有选择年度！");
                choiceCount = 0;
                return;
            }
            if (dgvZT.Rows.Count <= 0)
            {
                MessageBox.Show("没有需要导入的数据！");
                choiceCount = 0;
                return;
            }
            #endregion
            pbLoad.Value = 0;
            pbZLoad.Value = 0;
            pbLoad.Maximum = dgvZT.Rows.Count;
            pbZLoad.Maximum = choiceCount;
            lvZT.Enabled = false;
            btnCHOK.Enabled = false;
            lsYear.Enabled = false;
            dgvZT.Enabled = false;
            btnZTFileUrl.Enabled = false;
            tabChoice.Enabled = false;
            logTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyyMMddhhmmss");
            selsecZT(1);
        }

        private void selsecZT(int type)
        {
            pbLoad.Value = 0;
            for (int i = 0; i < lvZT.Items.Count; i++)
            {
                if (lvZT.Items[i].Checked == true)
                {
                    database = "UFDATA_" + lvZT.Items[i].SubItems[2].Text.ToString() + "_" + lsYear.SelectedItem.ToString();
                    databaseA = lvZT.Items[i].SubItems[1].Text.ToString();
                    lvZT.Items[i].Checked = false;
                    choiceCount--;
                    if (type == 1)
                    {
                        dbtype = lvZT.Items[i].SubItems[3].Text.ToString();
                        bgw1.RunWorkerAsync();//开始
                    }
                    if (type == 2)
                    {
                        UToN(database);
                        bgwPU.RunWorkerAsync();
                    }
                    if (type == 4)
                    {
                        UToN(database);
                        cusName = lvZT.Items[i].SubItems[1].Text.ToString();
                        bgwCus.RunWorkerAsync();
                    }
                    break;
                }
                if (choiceCount == 0)
                {
                    if (type == 1)
                    {
                        pbLoad.Value = pbLoad.Maximum;
                        txtZTFileUrl.Enabled = true;
                        btnCHOK.Enabled = true;
                        btnZTFileUrl.Enabled = true;
                        Process.Start("explorer.exe ", sb4 + "\\Log\\存货档案\\" + logTime);
                    }
                    if (type == 2 || type == 4)
                    {
                        DataGridViewToExcel(dgvZT2);
                    }
                    lvZT.Enabled = true;
                    lsYear.Enabled = true;
                    dgvZT.Enabled = true;
                    readChoice();
                    label4.Text = "";

                    switch (type)
                    { 
                        case 2:
                            bgwExcel.RunWorkerAsync();
                            break;
                        default:
                            MessageBox.Show("执行完毕！");
                            tabChoice.Enabled = true;
                            break;

                    }


                    //if (type != 2 || type != 4)
                    //{
                    //    MessageBox.Show("执行完毕！");
                    //    tabChoice.Enabled = true;
                    //}
                    //else
                    //{
                    //    if (type == 2)
                    //    {
                    //        bgwExcel.RunWorkerAsync();
                    //    }
                    //    if (type == 4)
                    //    {
                    //        bgwCus.RunWorkerAsync();
                    //    }
                    //}
                    break;
                }
            }
            pbZLoad.PerformStep();
        }

        #region 线程
        /// <summary>
        /// 线程开始转到的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgw1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT.Rows.Count; i++)
                {
                    dgvCount = i;
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgw1.CancelAsync();//结束
            }
        }

        /// <summary>
        /// 线程执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgw1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbLoad.PerformStep();
            int i = (int)e.UserState;
            string temp = dgvZT.Rows[i].Cells[1].Value.ToString();

            if (!dbtype.Equals(temp))//非对应的帐套跳过
            {
                if (!temp.Equals("POS"))
                {
                    i = i + 2;
                    label4.Text = database + "非对应的帐套跳过第" + i + "行\n";
                    txtInfo.Text += database + "非对应的帐套跳过第" + i + "行\n";
                    i = i - 2;
                    return;
                }
            }
            saleType = dgvZT.Rows[i].Cells[1].Value.ToString();
            cinvCode = dgvZT.Rows[i].Cells[2].Value.ToString();
            //if (cinvCode == "14590006")
            //{
            //}
            cinvName = dgvZT.Rows[i].Cells[6].Value.ToString();
            cinvStd = dgvZT.Rows[i].Cells[3].Value.ToString();
            NconvertU(dgvZT.Rows[i].Cells[13].Value.ToString());
            iInvWeight = dgvZT.Rows[i].Cells[4].Value.ToString();
            cComUnitCode = dgvZT.Rows[i].Cells[8].Value.ToString();
            iTaxUnitPrice = dgvZT.Rows[i].Cells[10].Value.ToString();
            //iTaxUnitPriceX = Convert.ToString(Convert.ToDouble(iTaxUnitPrice) / 1.13);
            iTaxUnitPriceX = iTaxUnitPrice;
            dStartDate = dgvZT.Rows[i].Cells[11].Value.ToString();
            dEnableDate = dgvZT.Rows[i].Cells[12].Value.ToString();
            dEDate = false;
            if (dEnableDate == "")
            {
                //DateTime dt = Convert.ToDateTime(dStartDate);
                //dEnableDate = dt.AddYears(5).ToString();
                //dEnableDate = null;
                dEDate = true;//不
            }
            else
            {
                //停
                if (getCurrentStock(cinvCode) == 0)
                {
                    dEDate = false;//停
                }
                else
                {
                    dEDate = true;//不
                }
            }
            if (temp.Equals("POS"))
            {
                if (selectInventory_cinvStd_cinvCode() > 0)
                {
                    if (select_SA_Price() > 0)//如果存货销售价格存在
                    {
                        update_SA_Price(i);//更新存货销售价格
                    }
                    else//如果存货销售不存在
                    {
                        insert_SA_Price(i);//插入存货销售价格
                    }
                }
                return;
            }
            Pos_Price(i);
            if (selectInventory() == "")//如果存货档案不存在
            {
                writeInventory(i, cinvCode, cinvName, cinvStd, cinvcCode, iInvWeight, cComUnitCode, dStartDate, iTaxUnitPrice, posPrice, dEnableDate, time);//插入存货
                //insert_PU_Price(i);//插入新存货采购价格
                if (select_PU_Price() > 0)//如果存货采购价格存在
                {
                    update_PU_Price(i);//更新存货采购价格
                }
                else//如果存货价格不存在
                {
                    insert_PU_Price(i);//插入存货采购价格
                }
                iTaxUnitPrice = posPrice;
                dStartDate = posdStartDate;
                dEnableDate = posdEndDate;
                if (select_SA_Price() > 0)//如果存货销售价格存在
                {
                    update_SA_Price(i);//更新存货销售价格
                }
                else//如果存货销售不存在
                {
                    insert_SA_Price(i);//插入存货销售价格
                }
            }
            else
            {
                if (tempCinvCode.Equals(cinvCode))
                {
                    updateInventory(iTaxUnitPrice, posPrice, dStartDate, dEnableDate, time, i, iInvWeight);
                    //insert_PU_Price(i);//插入新存货采购价格
                    if (select_PU_Price() > 0)//如果存货采购价格存在
                    {
                        update_PU_Price(i);//更新存货采购价格
                    }
                    else//如果存货价格不存在
                    {
                        insert_PU_Price(i);//插入存货采购价格
                    }
                    iTaxUnitPrice = posPrice;
                    dStartDate = posdStartDate;
                    dEnableDate = posdEndDate;
                    if (select_SA_Price() > 0)//如果存货销售价格存在
                    {
                        update_SA_Price(i);//更新存货销售价格
                    }
                    else//如果存货销售不存在
                    {
                        insert_SA_Price(i);//插入存货销售价格
                    }
                }
                else
                {
                    //有规格型号，但是存货编码匹配不上
                    if (cinvCode.Length > 8)
                    {
                        string tempCode22 = cinvCode;
                        cinvCode = cinvCode.Substring(0, 8);//取前8位
                        txtInfo.Text += "【" + tempCode22 + "】编码截取成8位【" + cinvCode + "】";
                        if (tempCinvCode.Length > 8)
                        {
                            if (!selectInventory_I())//检查,转换8位编码后的新编码是否存在
                            {
                                string tempCode23 = cinvCode;
                                //如果不存在 再匹配一次9位编码
                                selectInventory_Z();
                                txtInfo.Text += "【" + tempCode23 + "】编码模糊匹配了9位【" + cinvCode + "】";
                            }
                        }
                    }
                    else
                    {
                        string tempCode23 = cinvCode;
                        selectInventory_Z();
                        txtInfo.Text += "【" + tempCode23 + "】编码模糊匹配了9位【" + cinvCode + "】";
                    }
                    if (tempCinvCode.Equals(cinvCode))
                    {
                        updateInventory(iTaxUnitPrice, posPrice, dStartDate, dEnableDate, time, i, iInvWeight);
                        //insert_PU_Price(i);//插入新存货采购价格
                        if (select_PU_Price() > 0)//如果存货采购价格存在
                        {
                            update_PU_Price(i);//更新存货采购价格
                        }
                        else//如果存货价格不存在
                        {
                            insert_PU_Price(i);//插入存货采购价格
                        }
                        iTaxUnitPrice = posPrice;
                        dStartDate = posdStartDate;
                        dEnableDate = posdEndDate;
                        if (select_SA_Price() > 0)//如果存货销售价格存在
                        {
                            update_SA_Price(i);//更新存货销售价格
                        }
                        else//如果存货销售不存在
                        {
                            insert_SA_Price(i);//插入存货销售价格
                        }
                    }
                    else
                    {
                        i = i + 2;
                        label4.Text = database + ",第" + i + "行规格型号存在,但存货编码不一致,不导入存货档案";
                        txtInfo.Text += database + ",第" + i + "行规格型号存在,但存货编码不一致,不导入存货档案" + "\n";
                        i = i - 2;
                    }
                }
            }
        }

        private void updateInventory(string a, string b, string c, string d, string f,int i,string g)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            string sql = string.Empty;
            try
            {
                if (dEDate == true)
                {
//                    sql = string.Format(@"update Inventory set iInvSPrice ='{0}',iInvSCost ='{1}',dModifyDate='{2}',cModifyPerson='demo'
//                                        ,cinvdefine13='{3}',cinvdefine14='{4}',dSDate='{6}',dEDate=null, iinvweight='{8}',iImpTaxRate=0 where cInvCode='{5}'
//                                        ", a, b, f, a, b, cinvCode, c, d, g);
                    sql = string.Format(@"update Inventory set iInvSPrice ='{0}',iInvSCost ='{1}',dModifyDate='{2}',cModifyPerson='demo'
                                        ,cinvdefine13='{3}',dSDate='{4}',dEDate=null, iinvweight='{5}',iImpTaxRate=0 where cInvCode='{6}'
                                        ", a, b, f, g, c, g, cinvCode);
                }
                else
                {
//                    sql = string.Format(@"update Inventory set iInvSPrice ='{0}',iInvSCost ='{1}',dModifyDate='{2}',cModifyPerson='demo'
//                                        ,cinvdefine13='{3}',cinvdefine14='{4}',dSDate='{6}',dEDate='{7}', iinvweight='{8}',iImpTaxRate=0 where cInvCode='{5}'
//                                        ", a, b, f, a, b, cinvCode, c, d, g);
                    sql = string.Format(@"update Inventory set iInvSPrice ='{0}',iInvSCost ='{1}',dModifyDate='{2}',cModifyPerson='demo'
                                        ,cinvdefine13='{3}',dSDate='{5}',dEDate='{6}', iinvweight='{7}',iImpTaxRate=0 where cInvCode='{4}'
                                        ", a, b, f, g, cinvCode, c, d, g);
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            if (isok == 0)
            {
                i = i + 2;
                txtInfo.Text += database + ",第" + i + "行存货档案已存在,修改存货信息失败，原因" + errorInfo + "\n";
                label4.Text = database + ",第" + i + "行存货档案已存在,修改存货信息失败，原因" + errorInfo + "\n";
                i = i - 2;
            }
            else
            {
                i = i + 2;
                label4.Text = database + ",第" + i + "行存货档案已存在,修改存货信息成功" + "\n";
                txtInfo.Text += database + ",第" + i + "行存货档案已存在,修改存货信息成功" + "\n";
                i = i - 2;
            }
        }

        /// <summary>
        /// 线程结束转到的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bgw1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (txtInfo.Text != "")
            {
                logType = 1;
                btnLog.PerformClick();
                Process.Start("explorer.exe ", sb4 + "\\Log\\" + "存货档案\\" + logTime);
            }
            else
            {
                label4.Text = "没有可生成的日志信息";
            }
            selsecZT(1);
        }
        #endregion

        //查询存货表规格型号是否存在
        private string selectInventory()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cinvCode from Inventory where cinvstd='{0}'", cinvStd);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                tempCinvCode = Convert.ToString(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            return tempCinvCode;
        }

        //查询存货表存货编码是否存在
        private int selectInventory_cinvCode()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            try
            {
                string sql = string.Format("select count(*) from Inventory where cinvcode='{0}'", cinvCode);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            return isok;
        }

        private int selectInventory_cinvStd_cinvCode()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            try
            {
                string sql = string.Format("select count(*) from Inventory where cinvcode='{0}' and cinvstd='{1}'", cinvCode, cinvStd);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            return isok;
        }

        private void Pos_Price(int j)
        {
            string a;
            string b;
            for (int i = 0; i < dgvZT.Rows.Count; i++)
            {
                a = dgvZT.Rows[i].Cells[1].Value.ToString();
                b = dgvZT.Rows[i].Cells[2].Value.ToString();
                if (a.Equals("POS") && b.Equals(cinvCode))
                {
                    posPrice = dgvZT.Rows[i].Cells[10].Value.ToString();
                    posdStartDate = dgvZT.Rows[i].Cells[11].Value.ToString();
                    posdEndDate = dgvZT.Rows[i].Cells[12].Value.ToString();
                    break;
                }
            }
        }

        #region 采购价格
        ///<summary>
        /// 查询存货是否有采购价格
        ///</summary>
        ///<param name="i"></param>
        public int select_PU_Price()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int i = 0;
            try
            {
                string sql = string.Format("select count(*) from Ven_Inv_Price where cInvCode='{0}'", cinvCode);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                i = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            return i;
        }

        ///<summary>
        /// 更新存货采购价格
        ///</summary>
        ///<param name="i"></param>
        private void update_PU_Price(int i)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            string sql = string.Empty;
            try
            {
                if (dEDate == true)
                {
                    sql = string.Format(@"update Ven_Inv_Price set iunitPrice='{0}',iTaxUnitPrice ='{1}',dEnableDate='{2}'
                                        , dDisableDate=null,itaxrate=0 where cInvCode='{4}'", iTaxUnitPriceX, iTaxUnitPrice, dStartDate, null, cinvCode);
                }
                else
                {
                    sql = string.Format(@"update Ven_Inv_Price set iunitPrice='{0}',iTaxUnitPrice ='{1}',dEnableDate='{2}'
                                        , dDisableDate='{3}',itaxrate=0 where cInvCode='{4}'", iTaxUnitPriceX, iTaxUnitPrice, dStartDate, dEnableDate, cinvCode);
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                txtInfo.Text += database + ",第" + i + "行存货采购价格更新失败，原因" + errorInfo + "\n";
                label4.Text = database + ",第" + i + "行存货采购价格更新失败，原因" + errorInfo + "\n";
            }
            else
            {
                label4.Text = database + ",第" + i + "行存货采购价格更新成功" + "\n";
                txtInfo.Text += database + ",第" + i + "行存货采购价格更新成功" + "\n";
            }
        }

        ///<summary>
        /// 插入存货采购价格
        ///</summary>
        ///<param name="i"></param>
        private void insert_PU_Price(int i)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            string sql = string.Empty;
            try
            {
                if (dEDate == true)
                {
                    sql = string.Format(@"insert into Ven_Inv_Price (cVenCode,cInvCode,dEnableDate,cExch_Name,bPromotion,iSupplyType
                                        ,btaxcost,iLowerLimit,iunitPrice,iTaxRate,iTaxUnitPrice,ipriceautoid,dDisableDate) values 
                                        ('001','{0}','{1}','人民币',0,1,1,0,'{2}',0,'{3}',4,null)
                                        ", cinvCode, dStartDate, iTaxUnitPriceX, iTaxUnitPrice, null);
                }
                else
                {
                    sql = string.Format(@"insert into Ven_Inv_Price (cVenCode,cInvCode,dEnableDate,cExch_Name,bPromotion,iSupplyType
                                        ,btaxcost,iLowerLimit,iunitPrice,iTaxRate,iTaxUnitPrice,ipriceautoid,dDisableDate) values 
                                        ('001','{0}','{1}','人民币',0,1,1,0,'{2}',0,'{3}',4,'{4}')
                                        ", cinvCode, dStartDate, iTaxUnitPriceX, iTaxUnitPrice, dEnableDate);
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            if (isok == 0)
            {
                i = i + 2;
                txtInfo.Text += database + ",第" + i + "行新存货采购价格插入，原因" + errorInfo + "\n";
                label4.Text = database + ",第" + i + "行新存货采购价格插入，原因" + errorInfo + "\n";
            }
            else
            {
                i = i + 2;
                label4.Text = database + ",第" + i + "行新存货采购价格插入成功" + "\n";
                txtInfo.Text += database + ",第" + i + "行新存货采购价格插入成功" + "\n";
            }
        }
        #endregion

        #region 销售价格
        ///<summary>
        /// 查询存货是否有销售价格
        ///</summary>
        ///<param name="i"></param>
        public int select_SA_Price()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int i = 0;
            try
            {
                string sql = string.Format("select count(*) from SA_InvUPrice where cInvCode='{0}'", cinvCode);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                i = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            return i;
        }

        ///<summary>
        /// 更新存货销售价格
        ///</summary>
        ///<param name="i"></param>
        private void update_SA_Price(int i)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            string sql = string.Empty;
            try
            {
                if (dEDate == true)
                {
                    sql = string.Format(@"update SA_InvUPrice set iuPrice1='{0}',dstartdate='{1}',dEndDate=null where cInvCode='{3}'
                                        ", iTaxUnitPrice, dStartDate, null, cinvCode);
                }
                else
                {
                    sql = string.Format(@"update SA_InvUPrice set iuPrice1='{0}',dstartdate='{1}',dEndDate='{2}' where cInvCode='{3}'
                                        ", iTaxUnitPrice, dStartDate, dEnableDate, cinvCode);
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                txtInfo.Text += database + ",第" + i + "行存货销售价格更新失败，原因" + errorInfo + "\n";
                label4.Text = database + ",第" + i + "行存货销售价格更新失败，原因" + errorInfo + "\n";
            }
            else
            {
                label4.Text = database + ",第" + i + "行存货销售价格更新成功" + "\n";
                txtInfo.Text += database + ",第" + i + "行存货销售价格更新成功" + "\n";
            }
        }

        ///<summary>
        /// 插入存货销售价格
        ///</summary>
        ///<param name="i"></param>
        private void insert_SA_Price(int i)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            string sql = string.Empty;
            try
            {
                if (dEDate == true)
                {
                    sql = string.Format(@"insert into SA_InvUPrice(cInvCode,iuPrice1,dstartDate,fminquantity,binvalid,bsales,dEndDate
                                        )values ('{0}','{1}','{2}','0','False','False',null)", cinvCode, iTaxUnitPrice, dStartDate, null);
                }
                else
                {
                    sql = string.Format(@"insert into SA_InvUPrice(cInvCode,iuPrice1,dstartDate,fminquantity,binvalid,bsales,dEndDate
                                        )values ('{0}','{1}','{2}','0','False','False','{3}')", cinvCode, iTaxUnitPrice, dStartDate, dEnableDate);
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                txtInfo.Text += database + ",第" + i + "行新存货销售价格插入失败，原因" + sql + "\n";
                label4.Text = database + ",第" + i + "行新存货销售价格插入失败，原因" + errorInfo + "\n";
            }
            else
            {
                label4.Text = database + ",第" + i + "行新存货销售价格插入成功" + "\n";
                txtInfo.Text += database + ",第" + i + "行新存货销售价格插入成功" + "\n";
            }
        }
        #endregion

        #region ExcelToDataGridView
        private void btnFileUrl_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdZT = new OpenFileDialog();
            ofdZT.Filter = "Microsoft Excel 97-2003 工作表(*.xls)|*.xls";
            if (ofdZT.ShowDialog() == DialogResult.OK)
            {
                txtZTFileUrl.Text = ofdZT.FileName;
                excelUrl = ofdZT.FileName;
            }
            else
            {
                return;
            }
            DataTable importData = GetDataFromExcel(ofdZT.FileName);
            dgvZT.DataSource = importData;
            txtZTFileUrl.Enabled = false;
        }

        /// <summary>
        /// 获取指定 Excel 文件中工作表的数据。默认取第一个工作表。
        /// </summary>
        /// <param name="fileName">Excel 的文件名</param>
        /// <returns></returns>
        private DataTable GetDataFromExcel(String fileName)
        {
            string sheetName = GetExcelSheetNameByIndex(fileName, 0);
            if (!String.IsNullOrEmpty(sheetName))
            {
                string commandText = String.Format("SELECT * FROM [{0}]", sheetName);
                return ExecuteDataTable(fileName, commandText);
            }
            return null;
        }

        /// <summary>
        /// 获取 Excel 文件中指定索引的工作表名称
        /// </summary>
        /// <param name="fileName">Excel 的文件名</param>
        /// <param name="sheetIndex">要获取的索引</param>
        /// <returns></returns>
        private String GetExcelSheetNameByIndex(String fileName, int sheetIndex)
        {
            string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", fileName);
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();
                DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                return schemaTable.Rows.Count > sheetIndex
                    ? schemaTable.Rows[sheetIndex]["TABLE_NAME"].ToString()
                    : String.Empty;
            }
        }

        /// <summary>
        /// 获取指定 Excel 文件中工作表的数据。
        /// </summary>
        /// <param name="fileName">Excel 的文件名</param>
        /// <param name="commandText">查询 SQL </param>
        private DataTable ExecuteDataTable(String fileName, String commandText)
        {
            string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", fileName);
            using (OleDbDataAdapter da = new OleDbDataAdapter(commandText, connectionString))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                return ds.Tables[0];
            }
        }
        #endregion

        /// <summary>
        /// Navision存货分类转成U8存货分类
        /// </summary>
        /// <param name="nClass"></param>
        private void NconvertU(string nClass)
        {
            try
            {
                string sql = string.Format("select uclass from NconvertU where nclass='{0}'", nClass);
                SqlCommand com = new SqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                cinvcCode = Convert.ToString(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                DBHelper.con.Close();
            }
        }

        #region 存货档案
        /// <summary>
        /// 写入存货档案主表
        /// </summary>
        /// <param name="i"></param>
        private bool writeInventory(int i, string a, string b, string c, string d, string f, string g, string h, string j, string k, string l, string m)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            string sql = "";
            try
            {
                if (dEDate == true)
                {
                    sql = string.Format(@"insert into Inventory(cinvcode,cinvname,cinvstd,cinvccode,iInvWeight,cGroupCode,cComUnitCode,
                                        bsale,bpurchase,bExpSale,itaxrate,ccreateperson,cModifyPerson,dModifyDate,dsdate,iInvSPrice,
                                        iInvSCost,dEDate,iImpTaxRate) values ('{0}','{1}','{2}','{3}','{4}','01','{5}',1,1,1,13,'demo','demo',
                                        '{6}','{7}','{8}','{9}',null,0)", a, b, c, d, f, g, m, h, j, k, null);
                }
                else
                {
                    sql = string.Format(@"insert into Inventory(cinvcode,cinvname,cinvstd,cinvccode,iInvWeight,cGroupCode,cComUnitCode,
                                        bsale,bpurchase,bExpSale,itaxrate,ccreateperson,cModifyPerson,dModifyDate,dsdate,iInvSPrice,
                                        iInvSCost,dEDate,iImpTaxRate) values ('{0}','{1}','{2}','{3}','{4}','01','{5}',1,1,1,13,'demo','demo',
                                        '{6}','{7}','{8}','{9}','{10}',0)", a, b, c, d, f, g, m, h, j, k, l);
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                txtInfo.Text += database + ",第" + i + "行存货档案插入失败，原因" + sql + "\n";
                label4.Text = database + ",第" + i + "行存货档案插入失败，原因" + errorInfo;
                return false;
            }
            else
            {
                label4.Text = database + ",第" + i + "行存货档案插入成功";
                txtInfo.Text += database + ",第" + i + "行存货档案插入成功" + "\n";
                writeInventory_sub(i, a);
                return true;
            }
        }

        /// <summary>
        /// 写入存货档案副表
        /// </summary>
        /// <param name="i"></param>
        /// <param name="a"></param>
        /// <returns></returns>
        private void writeInventory_sub(int i, string a)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            try
            {
                string sql = string.Format("insert into Inventory_sub(cinvsubcode,bIsAttachFile,iExpiratDateCalcu,fInvCIQExch) values('{0}','False',0,1)", a);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            if (isok == 0)
            {
                txtInfo.Text += database + ",第" + i + "行存货档案副表插入失败，原因" + errorInfo + "\n";
                label4.Text = database + ",第" + i + "行存货档案副表插入失败，原因" + errorInfo;
            }
            else
            {
                bas_part(a, i);
                label4.Text = database + ",第" + i + "行存货档案副表插入成功";
                txtInfo.Text += database + ",第" + i + "行存货档案副表插入成功" + "\n";
            }
        }

        private void bas_part_Max()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = "select max(PartId) from bas_part";
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                partId = Convert.ToInt32(com.ExecuteScalar());
                partId = partId + 1;
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
        }

        private void bas_part(string a, int i)
        {
            bas_part_Max();
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            try
            {
                string sql = string.Format(@"insert into bas_part(PartId,InvCode,Free1,Free2,Free3,Free4,Free5,Free6,Free7,Free8,Free9,
                                        Free10,SafeQty,MinQty,MulQty,FixQty,bVirtual,iSurenessType) values 
                                        ({0},'{1}','','','','','','','','','','',null,null,null,null,'TRUE',1)", partId, a);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            if (isok == 0)
            {
                txtInfo.Text += database + ",第" + i + "行bas_part表插入失败，原因" + errorInfo + "\n";
                label4.Text = database + ",第" + i + "行bas_part表插入失败，原因" + errorInfo;
            }
            else
            {
                label4.Text = database + ",第" + i + "行bas_part表插入成功";
                txtInfo.Text += database + ",第" + i + "行bas_part表插入成功" + "\n";
            }
        }
        #endregion

        #region 全选 全不选
        private void btnAllChoice_Click(object sender, EventArgs e)
        {
            if (lvZT.Enabled == false)
            {
                MessageBox.Show("当前状态无法执行此项操作！");
                return;
            }
            for (int i = 0; i < lvZT.Items.Count; i++)
            {
                lvZT.Items[i].Checked = true;
            }
        }

        private void btnNotChoice_Click(object sender, EventArgs e)
        {
            if (lvZT.Enabled == false)
            {
                MessageBox.Show("当前状态无法执行此项操作！");
                return;
            }
            for (int i = 0; i < lvZT.Items.Count; i++)
            {
                lvZT.Items[i].Checked = false;
            }
        }
        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            if (account.ToLower() != "all")
            {
                MessageBox.Show("你没有权限打开该功能！");
                return;
            }
            Class c = new Class();
            c.ShowDialog();
        }

        /// <summary>
        /// 当前时间
        /// </summary>
        /// <returns></returns>
        private void data()
        {
            time = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyy-MM-dd hh:mm:ss");
        }

        private void tabChoice_SelectedIndexChanged(object sender, EventArgs e)
        {
            dgvZT.Columns.Clear();
            if (tabChoice.SelectedTab.Name.ToString() == "tabCH")
            {
                lvZT.Enabled = true;
                lsYear.Enabled = true;
                dgvZT.Visible = true;
                dgvZT2.Visible = false;
                readChoice();
                Width = 790;
            }
            if (tabChoice.SelectedTab.Name.ToString() == "tabPU")
            {
                lvZT.Enabled = true;
                lsYear.Enabled = true;
                dgvZT2.Visible = true;
                dgvZT.Visible = false;
                readChoice();
                Width = 790;
            }
            if (tabChoice.SelectedTab.Name.ToString() == "tabRD")
            {
                lvZT.Enabled = false;
                lsYear.Enabled = false;
                dgvZT.Visible = true;
                dgvZT2.Visible = false;
                Width = 428;
                StartPosition = FormStartPosition.CenterScreen;
            }

            if (tabChoice.SelectedTab.Name.ToString() == "tabCus")
            {
                lvZT.Enabled = true;
                lsYear.Enabled = true;
                dgvZT2.Visible = true;
                dgvZT.Visible = false;
                readChoice();
                Width = 790;
            }
            if (tabChoice.SelectedTab.Name.ToString() == "tabOther")
            {
                if (account.ToLower() != "all")
                {
                    MessageBox.Show("你没有权限打开该功能！");
                    tabChoice.SelectedTab = this.tabCH; 
                    return;
                }
                lvZT.Enabled = true;
                lsYear.Enabled = true;
                dgvZT.Visible = true;
                dgvZT2.Visible = false;
                readChoice();
                Width = 790;
            }
            txtZTFileUrl.Enabled = true;
            txtZTFileUrl.Text = "";
            txtRD.Enabled = true;
            txtRD.Text = "";
        }

        //下面开始 请购单
        private void btnPUOK_Click(object sender, EventArgs e)
        {
            dgvZT2.Columns.Clear();
            dgvColumn();
            recordChoice();
            #region 导出前的判断
            if (choiceCount < 1)
            {
                MessageBox.Show("没有选择帐套！");
                choiceCount = 0;
                return;
            }
            try
            {
                if (lsYear.SelectedItem.ToString() == "")
                {
                }
            }
            catch
            {
                MessageBox.Show("没有选择年度！");
                choiceCount = 0;
                return;
            }
            #endregion
            pbZLoad.Value = 0;
            pbZLoad.Maximum = choiceCount;
            tabChoice.Enabled = false;
            lvZT.Enabled = false;
            lsYear.Enabled = false;
            logTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyyMMddhhmmss");
            btnTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyMMdd");
            //MessageBox.Show(btnTime);
            selsecZT(2);
        }

        private void dgvColumn()
        {
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Flag");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "MSTC Order No.");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Salesperson Name");//null
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Customer No.");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Customer Name");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Order Date");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Comments (Max. 75 Char.)");//备注
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Item No.");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Qty");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Free");//0
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "Salesperson Code");//null
        }

        /// <summary>
        /// 执行导出
        /// </summary>
        /// <param name="ds">要导出的DataSet</param>
        /// <param name="strExcelFileName">要导出的文件名(详细路径加文件名)</param>
        private static void doExport(DataSet ds, string strExcelFileName)
        {
            Excel.Application excel = new Excel.Application();
            if (excel == null)
            {
                MessageBox.Show("无法启动Excel，可能您的电脑未安装Excel");
                return;
            }
            try
            {
                int rowIndex = 1;
                int colIndex = 0;
                excel.Application.Workbooks.Add(true);
                System.Data.DataTable table = ds.Tables[0];
                foreach (DataColumn col in table.Columns)
                {
                    colIndex++;
                    excel.Cells[1, colIndex] = col.ColumnName;
                }
                foreach (DataRow row in table.Rows)
                {
                    rowIndex++;
                    colIndex = 0;
                    foreach (DataColumn col in table.Columns)
                    {
                        colIndex++;
                        excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                    }
                }
                excel.Visible = false;
                //excel.Sheets[0] = "消息";
                excel.DisplayAlerts = false;
                excel.ActiveWorkbook.SaveCopyAs(strExcelFileName);

                excel.Quit();
                excel = null;
                MessageBox.Show("数据导出成功！", "消息", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                GC.Collect();//垃圾回收
            }
        }

        public void DataGridViewToExcel(DataGridView dgv)
        {
            int rowscount = dgvZT2.Rows.Count;
            int colscount = dgvZT2.Columns.Count;
            if (rowscount <= 0 || colscount <= 0)
            {
                MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (rowscount > 65536)
            {
                MessageBox.Show("数据记录数太多(最多不能超过65536条)，不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.DefaultExt = "xls ";
            dlg.Filter = "Microsoft Excel 97-2003 工作表(*.xls)|*.xls";
            dlg.InitialDirectory = Directory.GetCurrentDirectory();
            if (dlg.ShowDialog() == DialogResult.Cancel)
            {
                saveOK = 1;
                return;
            }
            string fileNameString = dlg.FileName;
            if (fileNameString.Trim() == " ")
            {
                return;
            }

            FileInfo file = new FileInfo(fileNameString);
            if (file.Exists)
            {
                try
                {
                    file.Delete();
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            Excel.Application objExcel = null;
            Excel.Workbook objWorkbook = null;
            Excel.Worksheet objsheet = null;
            try
            {
                objExcel = new Excel.Application();
                objWorkbook = objExcel.Workbooks.Add(Missing.Value);
                objsheet = (Excel.Worksheet)objWorkbook.ActiveSheet;
                objExcel.Visible = false;

                //表头 
                int displayColumnsCount = 1;
                for (int i = 0; i <= dgv.ColumnCount - 1; i++)
                {
                    if (dgv.Columns[i].Visible == true)
                    {
                        objExcel.Cells[1, displayColumnsCount] = dgv.Columns[i].HeaderText.Trim();
                        displayColumnsCount++;
                    }
                }
                //表体
                for (int row = 0; row <= dgv.RowCount - 1; row++)
                {
                    displayColumnsCount = 1;
                    for (int col = 0; col < colscount; col++)
                    {
                        if (dgv.Columns[col].Visible == true)
                        {
                            try
                            {
                                objExcel.Cells[row + 2, displayColumnsCount] = dgv.Rows[row].Cells[col].Value.ToString().Trim();
                                displayColumnsCount++;
                            }
                            catch (Exception)
                            {

                            }
                        }
                    }
                }
                objWorkbook.SaveAs(fileNameString, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                        Missing.Value, Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value,
                        Missing.Value, Missing.Value);
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            finally
            {
                //关闭Excel应用 
                if (objWorkbook != null) objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
                if (objExcel.Workbooks != null) objExcel.Workbooks.Close();
                if (objExcel != null) objExcel.Quit();

                objsheet = null;
                objWorkbook = null;
                objExcel = null;
            }
        }

        private void pu_code()
        {
            string temcodesss = uid.Substring(8, 2);
        }

        private void bgwPU_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
                string sql = "select a.ID as id,cCode,dDate,cInvCode,fQuantity,a.cDefine11 as cDefine11 from pu_appvouch as a inner join pu_appvouchs as b on a.ID=b.ID where cVerifier is  null";
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                using (SqlDataReader sdr = com.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        id = sdr["id"].ToString();
                        cCode = sdr["cCode"].ToString();
                        dDate = DateTime.Parse(sdr["dDate"].ToString()).ToString("yyyyMMdd");
                        cInvCode = sdr["cInvCode"].ToString();
                        fQuantity = sdr["fQuantity"].ToString();
                        bz = sdr["cDefine11"].ToString();
                        cCode = database.Substring(8, 2) + btnTime + cCode.Substring(cCode.Length - 4);
                        worker.ReportProgress(0);
                        Thread.Sleep(100);
                    }
                }
                con.Close();
                bgwPU.CancelAsync();
            }
        }

        private void bgwPU_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (tempCode == cCode)
            {
                dgvZT2.Rows.Add("Line", "@" + cCode, "", nid, databaseA, dDate, "", cInvCode, fQuantity, 0, "");
            }
            else
            {
                label4.Text = "正在获取" + database + "未审核请购单";
                dgvZT2.Rows.Add("Header", "@" + cCode, "", nid, databaseA, dDate, bz, "", "", "", "");
                dgvZT2.Rows.Add("Line", "@" + cCode, "", nid, databaseA, dDate, bz, cInvCode, fQuantity, 0, "");
            }
            tempCode = cCode;
        }

        private void bgwPU_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            tempCode = string.Empty;
            selsecZT(2);
        }

        private void select_PU()//没用到
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            string sql = "select a.ID as id,cCode,dDate,cInvCode,fQuantity,a.cDefine11 from pu_appvouch as a inner join pu_appvouchs as b on a.ID=b.ID where cVerifier is  null";
            SqlCommand com = new SqlCommand(sql, con);
            con.Open();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                string tempCode = string.Empty;
                while (sdr.Read())
                {
                    string id = sdr["id"].ToString();
                    string cCode = sdr["cCode"].ToString();
                    string dDate = sdr["dDate"].ToString();
                    string cInvCode = sdr["cInvCode"].ToString();
                    string fQuantity = sdr["fQuantity"].ToString();
                    dgvZT2.Rows.Add("Line", cCode, "", "", "", dDate, "", cInvCode, fQuantity, 0, "");
                    tempCode = cCode;
                }
            }
            con.Close();
        }

        /// <summary>
        /// U8帐套号转Navision帐套号
        /// </summary>
        /// <param name="nClass"></param>
        private void UToN(string db)
        {
            try
            {
                string sql = string.Format("select NID from NToU where UID='{0}'", db);
                SqlCommand com = new SqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                nid = Convert.ToString(com.ExecuteScalar());
            }
            catch
            {
                MessageBox.Show("转换帐套时失败");
                return;
            }
            finally
            {
                DBHelper.con.Close();
            }
        }

        private void NToU(string db)
        {
            try
            {
                string sql = string.Format("select UID from NToU where NID='{0}'", db);
                SqlCommand com = new SqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                uid = Convert.ToString(com.ExecuteScalar());
            }
            catch
            {
                MessageBox.Show("转换帐套时失败");
                return;
            }
            finally
            {
                DBHelper.con.Close();
            }
        }

        private void bgwExcel_DoWork(object sender, DoWorkEventArgs e)
        {
            if (saveOK > 0)
            {
                return;
            }
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT2.Rows.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgwExcel.CancelAsync();//结束
            }
        }

        private void bgwExcel_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int i = (int)e.UserState;
            string code = dgvZT2.Rows[i].Cells[7].Value.ToString();
            if (code == "")
            {
                string order = "000000"+ dgvZT2.Rows[i].Cells[1].Value.ToString().Substring(9);
                NToU(dgvZT2.Rows[i].Cells[3].Value.ToString());
                con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
                int isok = 0;
                try
                {
                    string sql = string.Format(@"update pu_appvouch set cVerifier ='{3}',cAuditDate='{0}',iverifystateex = 2,cAuditTime='{1}'
                                        where cCode='{2}'", time, time, order, uid.Substring(7, 3) + "01");
                    SqlCommand com = new SqlCommand(sql, con);
                    con.Open();
                    isok = Convert.ToInt32(com.ExecuteNonQuery());
                }
                catch (SqlException se)
                {
                    errorInfo = se.Number;
                }
                finally
                {
                    con.Close();
                }
                i = i + 2;
                if (isok == 0)
                {
                    txtInfo.Text += uid + "请购单" + order + "审核失败失败，原因" + errorInfo + "\n";
                    label4.Text = uid + "请购单" + order + "审核失败失败，原因" + errorInfo + "\n";
                }
                else
                {
                    label4.Text = uid + "请购单" + order + "审核成功，" + "\n";
                    txtInfo.Text += uid + "请购单" + order + "审核成功" + "\n";
                }
            }
        }

        private void bgwExcel_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("请购单导出、审核事件执行完成");
            tabChoice.Enabled = true;
            if (txtInfo.Text != "")
            {
                logType = 2;
                btnLog.PerformClick();
                Process.Start("explorer.exe ", sb4 + "\\Log\\" + "请购单\\" + logTime);
            }
            else
            {
                label4.Text = "没有可生成的日志信息";
            }
        }

        private void btnLog_Click(object sender, EventArgs e)
        {
            if (txtInfo.Text == "")
            {
                MessageBox.Show("没有日志！");
                return;
            }
            string s = "\n";
            string s1 = "\r\n";
            string str = this.txtInfo.Text;
            str = str.Replace(s, s1);
            string tempURL = string.Empty;
            string finalURL = string.Empty;
            if (logType == 1)
            {
                tempURL = sb4 + "\\Log\\" + "\\存货档案\\" + logTime;
                Directory.CreateDirectory(tempURL);
                finalURL = tempURL + "\\" + database + ".txt";
                logType = 0;
            }
            if (logType == 2)
            {
                tempURL = sb4 + "\\Log\\" + "\\请购单\\" + logTime;
                Directory.CreateDirectory(tempURL);
                finalURL = tempURL + "\\" + database + ".txt";
                logType = 0;
            }
            if (logType == 3)
            {
                tempURL = sb4 + "\\Log\\" + "\\采购入库单\\" + zt;
                Directory.CreateDirectory(tempURL);
                finalURL = tempURL + "\\0703" + logTime + ".txt";
                //MessageBox.Show(zt);
                logType = 0;
            }
            txtInfo.Text += finalURL;
            try
            {
                File.WriteAllText(finalURL, str);//保存日志
                txtInfo.Text = "";
            }
            catch
            {
                MessageBox.Show(database + ",日志文件生成失败！");
            }
        }

        //采购单入库单开始

        private bool selectInventory_X(int count)//查询存货编码是否存在
        {
            string tempX = string.Empty;
            string tempY = string.Empty;
            if (code == "")
            {
                return false;
            }
            else
            {
                if (count != 2)
                {
                    nullCode = code;
                }
            }
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cinvCode,dEDate from Inventory where cinvCode='{0}'", code );
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                try
                {
                    using (SqlDataReader sdr = com.ExecuteReader())
                    {
                        if (sdr.Read())
                        {
                            tempX = sdr["cinvCode"].ToString();
                            tempY = sdr["dEDate"].ToString();
                        }
                    }
                    if (tempX.Equals(code))
                    {
                        if (tempY == "")
                        {
                            return true;
                        }
                        else
                        {
                            DateTime Ts1 = Convert.ToDateTime(tempY);
                            DateTime Ts2 = Convert.ToDateTime(time);
                            if (Ts1 > Ts2)
                            {
                                return true;
                            }
                        }
                    }
                }
                catch
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                con.Close();
            }
            return false;
        }

        private void selectInventory_Y(int i)
        {
            string tempcode = code;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                //string sql = string.Format("select cinvCode from Inventory where cinvCode like '{0}%' and dEDate > '{1}'", code, time);
                string sql = string.Format("select cinvCode,dEDate from Inventory where cinvCode like '{0}%' and ( dEDate > '{1}' or dEDate='' or dEDate is null ) and cinvCode!='{2}'", code, time, nullCode);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                code = Convert.ToString(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (code != "")
            {
                txtInfo.Text += "在" + uid + "中" + tempcode + "模糊匹配了9位编码" + code + "【" + i + "】" + "\n";
            }
            else
            {
                txtInfo.Text += "在" + uid + "中" + nullCode + "无法匹配新编码【" + i + "】" + "\n";
            }
        }

        private void selectInventory_Z()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cinvCode from Inventory where cinvCode like '{0}%'", cinvCode);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                cinvCode = Convert.ToString(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
        }

        private bool selectInventory_I()
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select cinvCode from Inventory where cinvCode='{0}'", cinvCode);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                if (Convert.ToString(com.ExecuteScalar()).Equals(cinvCode))
                {
                    return true;
                }
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            return false;
        }

        //采购入库单是否存在
        private bool selectRdRecord()
        {
            int qwe = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select count(*) from RdRecord where ccode = '{0}'", order);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                qwe = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            if (qwe > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool selectPoMain()
        {
            int qwe = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = string.Format("select count(*) from po_pomain where cpoid = '{0}'", order);
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                qwe = Convert.ToInt32(com.ExecuteScalar());
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
            if (qwe > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private void btnRD_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofdZT = new OpenFileDialog();
            ofdZT.Filter = "文本文件(*.txt)|*.txt";
            if (ofdZT.ShowDialog() == DialogResult.OK)
            {
                txtRD.Text = ofdZT.FileName;
                excelUrl = ofdZT.FileName;
            }
            else
            {
                return;
            }
            //新建一个datatable用于保存读入的数据
            DataTable dt = new DataTable();
            //给datatable添加列
            dt.Columns.Add("TEANFA", typeof(String));
            dt.Columns.Add("TEANCC", typeof(String));
            dt.Columns.Add("TEANCL", typeof(String));
            dt.Columns.Add("TEANTR", typeof(String));
            dt.Columns.Add("LORYPL", typeof(String));
            dt.Columns.Add("RCITEM", typeof(String));
            dt.Columns.Add("RCUL", typeof(String));
            dt.Columns.Add("DUN", typeof(String));
            dt.Columns.Add("DUNQTY", typeof(String));
            dt.Columns.Add("ORDATE", typeof(String));
            dt.Columns.Add("LOADDT", typeof(String));
            dt.Columns.Add("LOADTM", typeof(String));
            dt.Columns.Add("DELDT", typeof(String));
            dt.Columns.Add("DELTM", typeof(String));
            dt.Columns.Add("LINE", typeof(String));
            dt.Columns.Add("COMMEN", typeof(String));
            dt.Columns.Add("ARTQTY", typeof(String));
            dt.Columns.Add("TDESA", typeof(String));
            dt.Columns.Add("TDESV", typeof(String));
            dt.Columns.Add("TRSCLT", typeof(String));
            dt.Columns.Add("TADR1", typeof(String));
            dt.Columns.Add("TADR2", typeof(String));
            dt.Columns.Add("TADR3", typeof(String));
            dt.Columns.Add("TCPOST", typeof(String));
            dt.Columns.Add("TVILLE", typeof(String));
            dt.Columns.Add("TREFCL", typeof(String));
            dt.Columns.Add("TNOPAL", typeof(String));
            dt.Columns.Add("TNOLOT", typeof(String));
            dt.Columns.Add("FABDT", typeof(String));
            dt.Columns.Add("FABTM", typeof(String));
            dt.Columns.Add("DLUODT", typeof(String));
            dt.Columns.Add("DLUOTM", typeof(String));
            //读入文件
            using (StreamReader reader = new StreamReader(ofdZT.FileName, Encoding.Default))
            {
                //循环读取所有行
                while (!reader.EndOfStream)
                {
                    //去除双引号,以分号截取
                    string[] data = reader.ReadLine().Replace("\"", "").Split(';');
                    //新建一行，并将读出的数据分段，分别存入对应的列中
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i <= 30; i++)
                    {
                        dr[i] = data[i];
                    }

                    //将这行数据加入到datatable中
                    dt.Rows.Add(dr);
                }
            }
            //将datatable绑定到datagridview上显示结果
            dgvZT.DataSource = dt;
            //删除第一行
            DataRowView drv = dgvZT.Rows[0].DataBoundItem as DataRowView;
            drv.Delete();
            txtRD.Enabled = false;
            logTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyyMMddhhmmss");
        }

        private void btnRDOK_Click(object sender, EventArgs e)
        {
            pbZLoad.Value = 0;
            pbLoad.Value = 0;
            pbZLoad.Maximum = 2;
            pbLoad.Maximum = dgvZT.Rows.Count * 2;
            pbZLoad.PerformStep();
            if (dgvZT.Rows.Count < 1)
            {
                MessageBox.Show("没有选择数据源！");
                choiceCount = 0;
                return;
            }
            bgwPO.RunWorkerAsync();
        }

        private void bgwPO_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT.Rows.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgwPO.CancelAsync();//结束
            }
        }

        private void bgwPO_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbLoad.PerformStep();
            int i = (int)e.UserState;
            zt = dgvZT.Rows[i].Cells[2].Value.ToString();
            order = dgvZT.Rows[i].Cells[4].Value.ToString();
            code = dgvZT.Rows[i].Cells[5].Value.ToString();
            count = dgvZT.Rows[i].Cells[8].Value.ToString();
            dateXX = DateTime.ParseExact(dgvZT.Rows[i].Cells[9].Value.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
            row = dgvZT.Rows[i].Cells[14].Value.ToString();
            //执行不同帐套时候，回写id
            priceA = "";
            priceB = "";
            if (tempZT != zt)
            {
                if (i == 0)
                {
                    //第一行时
                    maxDPoid(0);
                    maxMPoid(0);
                    setID_PO(0);
                    NToU(zt);
                }
                else
                {
                    //更改前一个帐套
                    maxDPoid(i - 1);
                    maxMPoid(i - 1);
                    setID_PO(i - 1);
                    maxDPoid(i);
                    maxMPoid(i);
                    setID_PO(i);
                    NToU(zt);
                }
                tempZT = zt;
            }
            if (zbAok == true)
            {
                if (!selectInventory_X(1))//如果存货档案不存在,或者已被停用
                {
                    if (code.Length > 8)//9位编码
                    {
                        string tempCode2 = code;
                        code = code.Substring(0, 8);//取前8位
                        i = i + 2;
                        txtInfo.Text += "在" + uid + "中新增采购订单时" + tempCode2 + "(因不存在,或已被停用),截取了前8位" + code + "【" + i + "】" + "\n";
                        i = i - 2;
                        if (!selectInventory_X(2))//检查,转换8位编码后的新编码是否存在
                        {
                            //如果不存在 再匹配一次9位编码
                            selectInventory_Y(i);//重新匹配出不为前一次不存在的编码
                        }
                        //如果还不存在，插入时写出日志
                    }
                    else
                    {
                        //8位编码模糊9位
                        selectInventory_Y(i);
                        //如果还不存在，插入时写出日志
                    }
                }
            }
            if (code != "")//如果匹配了一圈之后code变成空就不再继续执行
            {
                // return;
                //}
                //根据存货编码查询 采购含税价,不含税价
                GetPriceBYCode(code, zt);//取价格
                if (tempOrder != order)
                {
                    txtInfo.Text += "1:--------------------" + "\n";
                    zbAok = true;
                    //插入采购订单表头和表体第一行并审核
                    insert_PO_Main(i);
                    insert_PO_Details(i);
                    tempOrder = order;
                }
                else
                {
                    //插入采购订单表体
                    insert_PO_Details(i);
                }
                if (i + 1 == dgvZT.Rows.Count)
                {
                    maxDPoid(i);
                    maxMPoid(i);
                    setID_PO(i);
                    txtInfo.Text += "------采购订单结束----------" + "\n";
                }
            }
            else
            {
                txtInfo.Text += "------采购订单结束----------" + "\n";
            }
        }

        private void bgwPO_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            pbZLoad.PerformStep();
            tempOrder = "";
            tempZT = "";
            priceA = "";
            priceB = "";
            bgwRD.RunWorkerAsync();
        }

        private void bgwRD_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < dgvZT.Rows.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(100);
                }
                bgwRD.CancelAsync();//结束
            }
        }

        //库存线程
        private void bgwRD_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pbLoad.PerformStep();
            int i = (int)e.UserState;
            zt = dgvZT.Rows[i].Cells[2].Value.ToString();
            order = dgvZT.Rows[i].Cells[4].Value.ToString();
            code = dgvZT.Rows[i].Cells[5].Value.ToString();
            count = dgvZT.Rows[i].Cells[8].Value.ToString();
            dateXX = DateTime.ParseExact(dgvZT.Rows[i].Cells[9].Value.ToString(), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
            row = dgvZT.Rows[i].Cells[14].Value.ToString();
            priceA = "";
            priceB = "";
            if (tempZT != zt)
            {
                if (i == 0)
                {
                    maxDRDid(0);
                    maxMRDid(0);
                    setID_RD(0);
                    NToU(zt);
                }
                else
                {
                    //更改前一个帐套
                    maxDRDid(i - 1);
                    maxMRDid(i - 1);
                    setID_RD(i - 1);
                    maxDRDid(i);
                    maxMRDid(i);
                    setID_RD(i);
                    NToU(zt);
                }
                tempZT = zt;
            }
            if (zbBok == true)
            {
                if (!selectInventory_X(1))//如果存货档案不存在
                {
                    if (code.Length > 8)//9位编码
                    {
                        string tempCode2 = code;
                        code = code.Substring(0, 8);//取前8位
                        i = i + 2;
                        txtInfo.Text += "在" + uid + "中新增采购入库单时" + tempCode2 + "截取了前8位" + code + "【" + i + "】" + "\n";
                        i = i - 2;
                        if (!selectInventory_X(2))//检查,转换8位编码后的新编码是否存在
                        {
                            //如果不存在 再匹配一次9位编码
                            selectInventory_Y(i);
                        }
                        //如果还不存在，插入时写出日志
                    }
                    else
                    {
                        //8位编码,取前8位的模糊9位
                        selectInventory_Y(i);
                        //如果还不存在，插入时写出日志
                    }
                }
            }
            //if (code == "")
            //{
            //    return;
            //}
            //根据存货编码查询 采购含税价,不含税价
            GetPriceBYCode(code, zt);//取价格
            if (tempOrder != order)
            {
                txtInfo.Text += "2:-----------------" + "\n";
                if (i != 0)
                {
                    insert_Message(i - 1);
                }
                ii++;
                zbBok = true;
                //插入入库单表头和表体第一行,不审核
                insert_RdRecord(i);
                tempOrder = order;
                insert_RdRecords(i);
            }
            else
            {
                //插入入库单表体
                insert_RdRecords(i);
            }
            if (i + 1 == dgvZT.Rows.Count)
            {
                maxDRDid(i);
                maxMRDid(i);
                setID_RD(i);
                if (i == 0)
                {
                    insert_Message(i);
                }
                else
                {
                    insert_Message(i - 1);
                }
                txtInfo.Text += "3:------------------" + "\n";
            }
        }

        private void insert_Message(int i)
        {
            if (selectPoMain())
            {
                return;
            }
            string uidX = dgvZT.Rows[i].Cells[2].Value.ToString();
            order = dgvZT.Rows[i].Cells[4].Value.ToString();//
            NToU(uidX);
            int isok = 0;
            poidA++;
            try
            {
                string sql = string.Format(@"insert into ua_message(cMsgId,nMsgType,cMsgTitle,cMsgContent,cSender,cReceiver,dSend,
                                            nValidDay,bHasRead,nUrgent,DisplayPeriods,IsRemind,Account,Year) values 
                                            ('ea75011f-db7e-4298-b6ea-5df5f845d198',0,'采购单审核成功',
                                            '您的采购订单{4}已经审核通过,总价{5}元(如总价与实际订单价格不一致,以订单价格为主)
                                            ,手动整理现存量后正式入01仓库！多个订单入库只需整理一次','demo','{0}','{1}',1,'False'
                                            ,1,NULL,'True','{2}','{3}')
                                            ", uid.Substring(7, 3) + "01", time, uid.Substring(7, 3), uid.Substring(11, 4), order, sum[ii]);
                SqlCommand com = new SqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                DBHelper.con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                zbAok = false;
                txtInfo.Text += uid + "订单" + order + "消息发送失败，原因" + errorInfo + "\n";
                label4.Text = uid + "订单" + order + "消息发送失败，原因" + errorInfo;
            }
            else
            {
                label4.Text = uid + "订单" + order + "消息发送成功";
                txtInfo.Text += uid + "订单" + order + "消息发送成功" + "\n";
                i = i - 2;
                if (i+1 != dgvZT.Rows.Count)
                {
                    order = dgvZT.Rows[i + 1].Cells[4].Value.ToString();//
                    uidX = dgvZT.Rows[i + 1].Cells[2].Value.ToString();
                    NToU(uidX);
                }
            }
        }

        //获取库存采购税前和税后价格
        private void GetPriceBYCode(string code, string zt)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");

            string sql = string.Format("select iInvSPrice from Inventory where cInvCode='{0}'", code);
            SqlCommand com = new SqlCommand(sql, con);
            con.Open();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                if (sdr.Read())
                {
                    priceA = sdr["iInvSPrice"].ToString();//无税//没有用到
                    priceB = sdr["iInvSPrice"].ToString();//有税
                }
            }
            con.Close();
        }

        //获取采购订单主表最大ID
        private void maxMPoid(int i)
        {
            string uidX = dgvZT.Rows[i].Cells[2].Value.ToString();
            NToU(uidX);
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = "select max(poid) from po_pomain";
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                try
                {
                    poidA = Convert.ToInt32(com.ExecuteScalar());
                }
                catch
                {
                    poidA = 0;
                }
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
        }

        //获取采购订单子表最大ID
        private void maxDPoid(int i)
        {
            string uidX = dgvZT.Rows[i].Cells[2].Value.ToString();
            NToU(uidX);
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = "select max(id) from PO_Podetails";
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                try
                {
                    poidB = Convert.ToInt32(com.ExecuteScalar());
                }
                catch
                {
                    poidB = 0;
                }
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
        }

        //采购订单ID回写
        private void setID_PO(int i)
        {
            string uidX = dgvZT.Rows[i].Cells[2].Value.ToString();
            NToU(uidX);
            try
            {
                string sql = string.Format(@"update UA_Identity Set iFatherId='{0}',iChildId='{1}' Where cAcc_Id='{2}' And cVouchType='pomain'
                                        ", poidA, poidB, uid.Substring(7, 3));
                SqlCommand com = new SqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                com.ExecuteNonQuery();
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                DBHelper.con.Close();
            }
        }

        //插入采购主表
        private void insert_PO_Main(int i)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            poidA++;
            string sql = string.Empty;
            try
            {
                 sql = string.Format(@"insert into po_pomain (cPOID,dPODate,cVenCode,cPTCode,cexch_name,nflat,cMaker,cDefine7,
                                            POID,iVTid,iBG_OverFlag,cBG_Auditor,cBG_AuditTime,cDepCode,cPersonCode,cVerifier,cAuditTime
                                            ) values ('{0}','{1}','001','01','人民币',1,'{4}',null,{2},8173,null,null,null,null,null,
                                            '{5}','{3}')", order, dateXX, poidA, time, uid.Substring(7, 3) + "01", uid.Substring(7, 3) + "01");
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                zbAok = false;
                txtInfo.Text += uid + "新采购订单" + order + "创建失败,原因" + errorInfo + "【" + i + "】" + "\n";
                txtInfo.Text += sql;
                label4.Text = uid + "新采购订单" + order + "创建失败,原因" + errorInfo;
            }
            else
            {
                txtInfo.Text += uid + "新采购订单" + order + "创建成功【" + i + "】" + "\n";
                label4.Text = uid + "新采购订单" + order + "创建成功";
            }
        }

        //插入采购子表
        private void insert_PO_Details(int i)
        {
            if (zbAok == false)
            {
                return;
            }
            if (priceB == "")
            {
                i = i + 2;
                txtInfo.Text += uid + "新采购订单" + order + "插入商品" + code + "失败,原因" + "没有采购价格" + "【" + i + "】" + "\n";
                return;
            }
            DateTime dateYY = Convert.ToDateTime(dateXX);
            dateYY = dateYY.AddDays(1);
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            poidB++;
            try
            {
                string sql = string.Empty;
                if (priceB == "0")
                {
                    sql = string.Format(@"insert into po_poDetails(ID,cInvCode,iQuantity,dArriveDate,iPerTaxRate,cDefine26,
                                        cDefine27,POID,bTaxCost,cBG_ItemCode,cBG_ItemName,cBG_CaliberKey1,cBG_CaliberKeyName1,
                                        cBG_CaliberKey2,cBG_CaliberKeyName2,cBG_CaliberKey3,cBG_CaliberKeyName3,cBG_CaliberCode1,
                                        cBG_CaliberName1,cBG_CaliberCode2,cBG_CaliberName2,cBG_CaliberCode3,cBG_CaliberName3,
                                        iBG_Ctrl,cBG_Auditopinion,ivouchrowno,iUnitPrice,iMoney,iTax,iSum,iNatUnitPrice,iNatMoney,
                                        iNatTax,iNatSum,iTaxPrice)values({0},'{1}',{2},'{3}',0,null,null,{4},1,null,null,null,null
                                        ,null,null,null,null,null,null,null,null,null,null,null,null,{5},'{6}','{7}','{8}','{9}'
                                        ,'{10}','{11}','{12}','{13}','{14}')
                                        ", poidB, code, count, dateYY.ToString(), poidA, row, 0, 0, 0, 0, 0, 0, 0, 0, 0);
                }
                else
                {
                    sql = string.Format(@"insert into po_poDetails(ID,cInvCode,iQuantity,dArriveDate,iPerTaxRate,cDefine26,cDefine27
                                        ,POID,bTaxCost,cBG_ItemCode,cBG_ItemName,cBG_CaliberKey1,cBG_CaliberKeyName1,cBG_CaliberKey2
                                        ,cBG_CaliberKeyName2,cBG_CaliberKey3,cBG_CaliberKeyName3,cBG_CaliberCode1,cBG_CaliberName1
                                        ,cBG_CaliberCode2,cBG_CaliberName2,cBG_CaliberCode3,cBG_CaliberName3,iBG_Ctrl,cBG_Auditopinion
                                        ,ivouchrowno,iUnitPrice,iMoney,iTax,iSum,iNatUnitPrice,iNatMoney,iNatTax,iNatSum,iTaxPrice
                                        )values({0},'{1}',{2},'{3}',0,null,null,{4},1,null,null,null,null,null,null,null,null,null,null
                                        ,null,null,null,null,null,null,{5},'{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}')
                                        ", poidB, code, count, dateYY.ToString(), poidA, row, priceB
                                         , Convert.ToDouble(priceB) * Convert.ToDouble(count)
                                         , (Convert.ToDouble(priceB) * Convert.ToDouble(count)) - (Convert.ToDouble(priceB) * Convert.ToDouble(count))
                                         , Convert.ToDouble(priceB) * Convert.ToDouble(count)
                                         , Convert.ToDouble(priceB), Convert.ToDouble(priceB) * Convert.ToDouble(count)
                                         , (Convert.ToDouble(priceB) * Convert.ToDouble(count)) - (Convert.ToDouble(priceB) * Convert.ToDouble(count))
                                         , Convert.ToDouble(priceB) * Convert.ToDouble(count), priceB);
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {

                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                txtInfo.Text += uid + "新采购订单" + order + "插入商品" + code + "失败,原因" + errorInfo + "【" + i + "】" + "\n";
                label4.Text = uid + "新采购订单" + order + "插入商品" + code + "失败,原因" + errorInfo;
            }
            else
            {
                txtInfo.Text += uid + "新采购订单" + order + "插入商品" + code + "成功【" + i + "】" + "\n";
                label4.Text = uid + "新采购订单" + order + "插入商品" + code + "成功";
            }
        }

        private void insert_RdRecord(int i)
        {
            if (!selectRdRecord())
            {
                i = i + 2;
                zbBok = false;
                txtInfo.Text += "在" + uid + "中采购入库单" + order + "已存在！【" + i + "】" + "\n";
                return;
            }
            if (selectPoMain())
            {
                i = i + 2;
                zbBok = false;
                txtInfo.Text += "在" + uid + "中未检测到采购订单" + order + ",不导入该采购入库单！【" + i + "】" + "\n";
                return;
            }
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            rdidA++;
            try
            {
                string sql = string.Format(@"insert into RdRecord (ID,cVouchType,cBusType,cSource,bRdFlag,cWhCode,dDate,cCode
                                        ,cRdCode,cDepCode,cPersonCode,cPTCode,cVenCode,cOrderCode,cMaker,VT_ID,ipurorderid,iTaxRate
                                        ,iExchRate,cExch_Name,bOMFirst,dnmaketime,bCredit) values ({0},'01','普通采购','库存',1,'01'
                                        ,'{1}','{2}','101',null,null,'01','001',null,'{4}','27',null,0,1,'人民币',0,'{3}',0)
                                        ", rdidA, time.Substring(0, 11), order, dateXX, uid.Substring(7, 3) + "01");
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                zbBok = false;
                txtInfo.Text += uid + "新采购入库单" + order + "创建失败,原因" + errorInfo + "【" + i + "】" + "\n";
                label4.Text = uid + "新采购入库单" + order + "创建失败,原因" + errorInfo;
            }
            else
            {
                txtInfo.Text += uid + "新采购入库单" + order + "创建成功【" + i + "】" + "\n";
                label4.Text = uid + "新采购入库单" + order + "创建成功";
            }
        }

        private void insert_RdRecords(int i)
        {
            if (zbBok == false)
            {
                return;
            }
            if (priceB == "")
            {
                i = i + 2;
                txtInfo.Text += uid + "新采购入库单" + order + "插入商品" + code + "失败，原因" + "没有采购价格" + "【" + i + "】" + "\n";
                return;
            }
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            rdidB++;
            try
            {
                string sql = string.Empty;
                if (priceB == "0")
                {
                    sql = string.Format(@"insert into RdRecords(AutoID,ID,cInvCode,iQuantity,iTax,iFNum,iFQuantity,iPOsID,
                                        iDlsID,iSendQuantity,iSendNum,iNQuantity,bTaxCost,cPOID,iordertype,iSumBillQuantity,
                                        bVMIused,corufts,isotype,irowno,bCosting,cbaccounter,iSOutQuantity,isoutnum,
                                        iVMISettleQuantity,iUnitCost,iPrice,iAPrice,fACost,iOriTaxCost,iOriCost,iOriMoney,
                                        iOriTaxPrice,ioriSum,iTaxRate,iTaxPrice,iSum)values({0},{1},'{2}','{3}','0',null,null,
                                        null,null,'0','0',null,'1',null,null,null,'0',null,null,{4},'1',null,null,null,null,'{5}'
                                        ,'{6}','{6}','{7}','{8}','{9}','{10}','0.00','{11}','0.00','0.00','{12}')
                                        ", rdidB, rdidA, code, count, row, 0, 0, 0, 0, 0, 0, 0, 0, 0);
                }
                else
                {
                    sql = string.Format(@"insert into RdRecords(AutoID,ID,cInvCode,iQuantity,iTax,iFNum,iFQuantity,iPOsID,
                                        iDlsID,iSendQuantity,iSendNum,iNQuantity,bTaxCost,cPOID,iordertype,iSumBillQuantity,
                                        bVMIused,corufts,isotype,irowno,bCosting,cbaccounter,iSOutQuantity,isoutnum,
                                        iVMISettleQuantity,iUnitCost,iPrice,iAPrice,fACost,iOriTaxCost,iOriCost,iOriMoney,
                                        iOriTaxPrice,ioriSum,iTaxRate,iTaxPrice,iSum)values({0},{1},'{2}','{3}','0',null,
                                        null,null,null,'0','0',null,'1',null,null,null,'0',null,null,{4},'1',null,null,
                                        null,null,'{5}','{6}','{6}','{7}','{8}','{9}','{10}','0.00','{11}','0.00','0.00','{12}')
                                        ", rdidB, rdidA, code, count, row, priceB, Convert.ToDouble(priceB) * Convert.ToDouble(count),
                                         Convert.ToDouble(priceB) * Convert.ToDouble(count), priceB, priceB, priceB, 
                                         Convert.ToDouble(priceB) * Convert.ToDouble(count), Convert.ToDouble(priceB) * 
                                         Convert.ToDouble(count), Convert.ToDouble(priceB) * Convert.ToDouble(count));
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            i = i + 2;
            if (isok == 0)
            {
                txtInfo.Text += uid + "新采购入库单" + order + "插入商品" + code + "失败，原因" + errorInfo + "【" + i + "】" + "\n";
                label4.Text = uid + "新采购入库单" + order + "插入商品" + code + "失败，原因" + errorInfo;
            }
            else
            {
                sum[ii] += Convert.ToDouble(priceB) * Convert.ToDouble(count);
                txtInfo.Text += uid + "新采购入库单" + order + "插入商品" + code + "成功【" + i + "】" + "\n";
                label4.Text = uid + "新采购入库单" + order + "插入商品" + code + "成功";
            }
        }

        //获取入库单主表最大ID
        private void maxMRDid(int i)
        {
            string uidX = dgvZT.Rows[i].Cells[2].Value.ToString();
            NToU(uidX);
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = "select max(id) from RdRecord";
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                try
                {
                    rdidA = Convert.ToInt32(com.ExecuteScalar());
                }
                catch
                {
                    rdidA = 0;
                }
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
        }

        //获取入库单子表最大ID
        private void maxDRDid(int i)
        {
            string uidX = dgvZT.Rows[i].Cells[2].Value.ToString();
            NToU(uidX);
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + uid + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            try
            {
                string sql = "select max(autoid) from RdRecords";
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                try
                {
                    rdidB = Convert.ToInt32(com.ExecuteScalar());
                }
                catch
                {
                    rdidB = 0;
                }
            }
            catch
            {
            }
            finally
            {
                con.Close();
            }
        }

        //采购入库单ID回写
        private void setID_RD(int i)
        {
            string uidX = dgvZT.Rows[i].Cells[2].Value.ToString();
            NToU(uidX);
            try
            {
                string sql = string.Format("update UA_Identity Set iFatherId='{0}',iChildId='{1}' Where cAcc_Id='{2}' And cVouchType='rd'", rdidA, rdidB, uid.Substring(7, 3));
                SqlCommand com = new SqlCommand(sql, DBHelper.con);
                DBHelper.con.Open();
                com.ExecuteNonQuery();
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                DBHelper.con.Close();
            }
        }

        private void bgwRD_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            tempOrder = "";
            tempZT = "";
            priceA = "";
            priceB = "";
            poidA = 0;//采购主表最大id
            poidB = 0;//采购子表最大id
            rdidA = 0;//入库单主表最大id
            rdidB = 0;//入库单子表最大id
            row = string.Empty;
            oldID = string.Empty;
            zbAok = true;
            zbBok = true;
            logType = 0;
            ii = 0;
            nullCode = string.Empty;//检测为不存在的存货编码


            if (txtInfo.Text != "")
            {
                logType = 3;
                btnLog.PerformClick();
                Process.Start("explorer.exe ", sb4 + "\\Log\\" + "采购入库单\\" + zt);
            }
            else
            {
                label4.Text = "没有可生成的日志信息";
            }
            MessageBox.Show("采购入库单导入事件执行完毕！");
        }

        private void btnZT_Click(object sender, EventArgs e)
        {
            if (account.ToLower() != "all")
            {
                MessageBox.Show("你没有权限打开该功能！");
                return;
            }
            UToN u = new UToN();
            u.ShowDialog();
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void btnPrice_Click(object sender, EventArgs e)
        {
            recordChoice();
            if (choiceCount < 1)
            {
                MessageBox.Show("没有选择帐套！");
                choiceCount = 0;
                return;
            }
            pbZLoad.Value = 0;
            pbLoad.Value = 0;
            pbZLoad.Maximum = choiceCount;
            otherType = 1;
            tabChoice.Enabled = false;
            lsYear.Enabled = false;
            btnAllChoice.Enabled = false;
            btnNotChoice.Enabled = false;
            bgwPrice.RunWorkerAsync();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            recordChoice();
            if (choiceCount < 1)
            {
                MessageBox.Show("没有选择帐套！");
                choiceCount = 0;
                return;
            }
            pbZLoad.Value = 0;
            pbLoad.Value = 0;
            pbZLoad.Maximum = choiceCount;
            otherType = 2;
            tabChoice.Enabled = false;
            lsYear.Enabled = false;
            btnAllChoice.Enabled = false;
            btnNotChoice.Enabled = false;
            bgwPrice.RunWorkerAsync();
        }

        private void bgwPrice_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                for (int i = 0; i < lvZT.Items.Count; i++)
                {
                    worker.ReportProgress(0, i);
                    Thread.Sleep(1000);
                }
                bgwPrice.CancelAsync();//结束
            }
        }

        private void bgwPrice_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int i = Convert.ToInt32(e.UserState);
            if (lvZT.Items[i].Checked == true)
            {
                database = "UFDATA_" + lvZT.Items[i].SubItems[2].Text.ToString() + "_" + lsYear.SelectedItem.ToString();
                lvZT.Items[i].Checked = false;
                switch (otherType)
                {
                    case 1:
                        updateOther(1);
                        updateOther(2);
                        //updateOther(4);
                        //updateOther(5);
                        break;
                    case 2:
                        updateOther(3);
                        break;
                }
                pbZLoad.PerformStep();
                choiceCount--;
            }
        }

        private void bgwPrice_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("更新完成！");
            tabChoice.Enabled = true;
            lsYear.Enabled = true;
            btnAllChoice.Enabled = true;
            btnNotChoice.Enabled = true;
            readChoice();
        }

        private void updateOther(int type)
        {
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            int isok = 0;
            string sql = string.Empty;
            try
            {
                switch (type)
                {
                    case 1://更新参考售价
                        sql = "update inventory set iinvscost=0 where iinvscost is null";
                        break;
                    case 2://更新参考售成本
                        sql = "update inventory set iInvSPrice=0 where iInvSPrice is null";
                        break;
                    case 3://更新停用日期
                        sql = "update inventory set dedate=dsdate+1825 where dedate is null";
                        break;
                    case 4://更新参考售价
                        sql = "update inventory set iImpTaxRate=0";
                        break;
                    case 5://更新参考售成本
                        sql = "update Ven_Inv_Price set itaxrate=0 ,iunitprice=itaxunitprice ";
                        break;
                }
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                isok = Convert.ToInt32(com.ExecuteNonQuery());
            }
            catch (SqlException e)
            {
                errorInfo = e.Number;
            }
            finally
            {
                con.Close();
            }
            switch (type)
            {
                case 1://更新参考售价
                    txtInfo.Text += database + ",更共更新" + isok + "条参考售价";
                    label4.Text = database + ",更共更新" + isok + "条参考售价";
                    break;
                case 2://更新参考成本
                    txtInfo.Text += database + ",更共更新" + isok + "条参考成本";
                    label4.Text = database + ",更共更新" + isok + "条参考成本";
                    break;
                case 3://更新停用日期
                    txtInfo.Text += database + ",更共更新" + isok + "条停用日期";
                    label4.Text = database + ",更共更新" + isok + "条停用日期";
                    break;
            }
        }

        int selectCount = 0;
        private void lvZT_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (lvZT.Enabled == false)
            {
                return;
            }
            for (int i = 0; i < lvZT.Items.Count; i++)
            {
                if (lvZT.Items[i].Checked)
                {
                    selectCount++;
                }
            }
            label8.Text = "已选择 " + selectCount.ToString() + " 个帐套";
            selectCount = 0;
        }

        //客户档案导出线程开始
        private void btnCusOK_Click(object sender, EventArgs e)
        {
            dgvZT2.Columns.Clear();
            dgvCusColumn();
            recordChoice();
            #region 导出前的判断
            if (choiceCount < 1)
            {
                MessageBox.Show("没有选择帐套！");
                choiceCount = 0;
                return;
            }
            try
            {
                if (lsYear.SelectedItem.ToString() == "")
                {
                }
            }
            catch
            {
                MessageBox.Show("没有选择年度！");
                choiceCount = 0;
                return;
            }
            #endregion
            pbZLoad.Value = 0;
            pbZLoad.Maximum = choiceCount;
            tabChoice.Enabled = false;
            lvZT.Enabled = false;
            lsYear.Enabled = false;
            logTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyyyMMddhhmmss");
            btnTime = DateTime.Parse(DateTime.Now.ToString()).ToString("yyMMdd");
            //MessageBox.Show(btnTime);
            selsecZT(4);
        }

        private void dgvCusColumn()
        {
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "经销商名称");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "经销商代码");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "渠道");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "店型");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "门店编码");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "门店名称");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "门店简称");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "联系人");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "地址");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "电话");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "启用日期");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "停用日期");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "专管业务员");
            dgvZT2.Columns.Add(new DataGridViewTextBoxColumn().ToString(), "业务员编码");
        }

        private void bgwCus_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            while (worker.CancellationPending == false)
            {
                con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
                string sql = "select c.cccname as 渠道,d.ccusrankname as 店型,a.ccusname as 门店名称,a.ccusabbname as 门店简称,a.ccusperson as 联系人,a.ccusaddress as 地址,a.ccusphone as 电话,a.ccushand as 手机,a.dcusdevdate as 启用日期,a.denddate as 停用日期,b.cpersonname as 专管业务员,b.cpersoncode as 业务员编码, a.ccuscode as 门店编码 from Customer as a left join Person as b on a.ccuspperson=b.cpersoncode left join CustomerClass as c on a.ccccode=c.ccccode left join CustomerRank as d on a.customerkcode=d.ccusrankcode";
                SqlCommand com = new SqlCommand(sql, con);
                con.Open();
                using (SqlDataReader sdr = com.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        cccname = sdr["渠道"].ToString();
                        ccusrankname = sdr["店型"].ToString();
                        ccuscode = sdr["门店编码"].ToString();
                        ccusname = sdr["门店名称"].ToString();
                        ccusabbname = sdr["门店简称"].ToString();
                        ccusperson = sdr["联系人"].ToString();
                        ccusaddress = sdr["地址"].ToString();
                        ccusphone = sdr["电话"].ToString();
                        ccushand = sdr["手机"].ToString();
                        dcusdevdate = sdr["启用日期"].ToString();
                        denddate = sdr["停用日期"].ToString();
                        cpersonname = sdr["专管业务员"].ToString();
                        cpersoncode = sdr["业务员编码"].ToString();
                        worker.ReportProgress(0);
                        Thread.Sleep(100);
                    }
                }
                con.Close();
                bgwCus.CancelAsync();
            }
        }

        private void bgwCus_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            label4.Text = "正在获取" + database + "的客户信息";
            if (ccusphone == "")
            {
                ccusphone = ccushand;
            }
            dgvZT2.Rows.Add(cusName, nid, cccname, ccusrankname, "'" + ccuscode, ccusname, ccusabbname, ccusperson, ccusaddress, ccusphone, dcusdevdate, denddate, cpersonname, "'" + cpersoncode);
        }

        private void bgwCus_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            selsecZT(4);
        }

        /// <summary>
        /// 检测现存量
        /// </summary>
        /// <param name="invId"></param>
        /// <returns></returns>
        public double getCurrentStock(string invId)
        {
            double bb = 0;
            con = new SqlConnection("Data Source=" + sb1 + ";Initial Catalog=" + database + ";User ID=" + sb2 + ";Password=" + sb3 + "");
            string sql = string.Format("Select sum(iQuantity) as sl,SUM(ISNULL(iQuantity,0) +ISNULL(fInQuantity,0) - ISNULL(fOutQuantity,0)) as xcl From CurrentStock  where cInvCode='{0}' and isnull(bStopFlag,0)=0", invId);
            SqlCommand com = new SqlCommand(sql, con);
            con.Open();
            using (SqlDataReader sdr = com.ExecuteReader())
            {
                while (sdr.Read())
                {
                    try
                    {
                        bb = Convert.ToDouble(sdr["xcl"].ToString());//现存量
                    }
                    catch
                    {
                        bb = 0;
                    }
                }
            }
            con.Close();
            return bb;
        }
    }
}